package com.example.sunmiv1.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.GiftGoodsAdapter;
import com.example.sunmiv1.base.BaseActivity;
import com.example.sunmiv1.entity.GiftGoodsInfo;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.utils.zxing.Constant;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.content.ContentValues.TAG;

public class ChooseGiftGoodsActivity extends BaseActivity {


    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.giveGoods_edit)
    EditText giveGoodsEdit;
    @BindView(R.id.giveGoods_searchLinear)
    LinearLayout giveGoodsSearchLinear;
    @BindView(R.id.giveGoods_listView)
    PullToRefreshListView giveGoodsListView;
    @BindView(R.id.scan_giveGoods)
    ImageView scanGiveGoods;
    @BindView(R.id.search_giveGoods)
    ImageView searchGiveGoods;
    @BindView(R.id.giveGoods_noGiftGood)
    LinearLayout giveGoodsNoGiftGood;

    private int page = 1;
    private GiftGoodsInfo giftGoodsInfo;
    private List<GiftGoodsInfo.DataBean.ListBean> goodsList = new ArrayList<>();
    private LoadingDialog loadingDialog;
    private GiftGoodsAdapter giftGoodsAdapter;
    private int allChooseNum = 0;
    private List<GiftGoodsInfo.DataBean.ListBean> chooseList = new ArrayList<>();

    private ACache aCache;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    page++;
                    for (GiftGoodsInfo.DataBean.ListBean listBean : giftGoodsInfo.getData().getList()) {
                        if (chooseList.size() > 0) {
                            for (int i = 0; i < chooseList.size(); i++) {
                                if (listBean.getId().equals(chooseList.get(i).getId())&&listBean.getGoods_gifts_id().equals(chooseList.get(i).getGoods_gifts_id())) {
                                    listBean.setChooseNum(chooseList.get(i).getChooseNum());
                                }
                            }
                        } else {
                            listBean.setChooseNum(0);
                        }
                    }
                    goodsList.addAll(giftGoodsInfo.getData().getList());
                    setGiftGoodsAdapter();
                    break;
                case 2:
                    setGiftGoodsAdapter();
                    break;
            }
        }
    };


    @Override
    protected void initView() {
        setContentView(R.layout.activity_choose_gift_goods);
        ButterKnife.bind(this);
        context = this;
        aCache = ACache.get(this);
        loadingDialog = new LoadingDialog(context);
        titleTitle.setText(R.string.chooseGiftTitle);
    }

    @Override
    protected void initData() {
        allChooseNum = getIntent().getIntExtra("giftGoodsNum", 0);
        chooseList = (List<GiftGoodsInfo.DataBean.ListBean>) getIntent().getSerializableExtra("choose_list");
        getGifGoods();
    }

    @Override
    protected void initListener() {
        giveGoodsListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                page = 1;
                goodsList.clear();
                setGiftGoodsAdapter();
                getGifGoods();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                getGifGoods();
            }
        });
        giveGoodsEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(giveGoodsEdit.getText().toString().trim())) {
                    page = 1;
                    goodsList.clear();
                    setGiftGoodsAdapter();
                    getGifGoods();
                }
            }
        });
        giveGoodsEdit.setOnEditorActionListener((v, actionId, event) -> {
            if (getBoolean(actionId, event)) {
                page = 1;
                goodsList.clear();
                setGiftGoodsAdapter();
                getGifGoods();
            }
            return false;
        });
    }

    /**
     * 判斷是否點擊回車事件
     */
    private boolean getBoolean(int actionId, KeyEvent event) {
        boolean e = actionId == EditorInfo.IME_ACTION_SEND
                || actionId == EditorInfo.IME_ACTION_DONE
                || (event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction());
        return e;
    }

    private void setGiftGoodsAdapter() {
        if (goodsList.size() == 0) {
            giveGoodsNoGiftGood.setVisibility(View.VISIBLE);
            giveGoodsListView.setVisibility(View.GONE);
        } else {
            giveGoodsNoGiftGood.setVisibility(View.GONE);
            giveGoodsListView.setVisibility(View.VISIBLE);
        }
        if (giftGoodsAdapter == null) {
            giftGoodsAdapter = new GiftGoodsAdapter(goodsList);
            giveGoodsListView.setAdapter(giftGoodsAdapter);
        } else {
            giftGoodsAdapter.notifyDataSetChanged();
        }
        giftGoodsAdapter.Click((flag, index) -> {
            Log.e(TAG, "setGiftGoodsAdapter: ====" + index);
            boolean b = false;
            int position = 0;
            for (int i = 0; i < chooseList.size(); i++) {
                if (chooseList.get(i).getGoods_gifts_id().equals(goodsList.get(index).getGoods_gifts_id())) {
                    b = true;
                    position = i;
                    break;
                }
            }
            if (flag == 1) {//加商品
                Log.e(TAG, "setGiftGoodsAdapter: ====" + position);
                if (Integer.parseInt(aCache.getAsString("goods_gifts_num")) == allChooseNum) {
                    Toast.makeText(context, "不能繼續添加了", Toast.LENGTH_SHORT).show();
                    return;
                }
                allChooseNum++;
                goodsList.get(index).setChooseNum(goodsList.get(index).getChooseNum() + 1);
                if (!b) {
                    chooseList.add(goodsList.get(index));
                }
            } else {
                allChooseNum--;
                goodsList.get(index).setChooseNum(goodsList.get(index).getChooseNum() - 1);
                if (b) {
                    if (chooseList.get(position).getChooseNum() == 1) {
                        chooseList.remove(position);
                    }
                }
            }
            giftGoodsAdapter.notifyDataSetChanged();
        });
    }

    /**
     * 獲取贈送商品
     */
    private void getGifGoods() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("page", page);
            jsonObject.put("pageSize", 20);
            jsonObject.put("search", giveGoodsEdit.getText().toString().trim());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        jsonObject = Tools.createParameterCode(jsonObject);
        HttpUtils.post(Objects.requireNonNull(context), Common.GET_GIF_GOODS, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                loadingDialog.dismiss();
                giveGoodsListView.onRefreshComplete();
                giftGoodsInfo = GsonUtils.JsonToBean(text, GiftGoodsInfo.class);
                Message msg = new Message();
                if (giftGoodsInfo.getStatus() == 1) {
                    msg.what = 1;
                } else {
                    msg.what = 2;
                }
                handler.sendMessage(msg);
            }

            @Override
            protected void onFailure(ResponseException e) {
                loadingDialog.dismiss();
                giveGoodsListView.onRefreshComplete();
            }
        });
    }

    /* 監聽手機系統返回鍵*/
    @Override
    public void onBackPressed() {
        Intent intent = new Intent(context, CollectingSilverActivity.class);
        intent.putExtra("choose_list", (Serializable) chooseList);
        intent.putExtra("allChooseNum", allChooseNum);
        setResult(RESULT_OK, intent);
        finish();
    }


    @OnClick({R.id.title_back, R.id.search_giveGoods, R.id.scan_giveGoods})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                Intent intent = new Intent(context, CollectingSilverActivity.class);
                intent.putExtra("choose_list", (Serializable) chooseList);
                intent.putExtra("allChooseNum", allChooseNum);
                setResult(RESULT_OK, intent);
                finish();
                break;
            case R.id.search_giveGoods:
                if (TextUtils.isEmpty(giveGoodsEdit.getText().toString().trim())) {
                    Toast.makeText(this, "請輸入要搜索的內容", Toast.LENGTH_SHORT).show();
                    return;
                }
                page = 1;
                goodsList.clear();
                setGiftGoodsAdapter();
                getGifGoods();
                break;
            case R.id.scan_giveGoods:
                startQrCode();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode != 1 && requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {//掃描結果回調
            Bundle bundle = data.getExtras();
            giveGoodsEdit.setText(bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN));
            page = 1;
            goodsList.clear();
            setGiftGoodsAdapter();
            getGifGoods();
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
